package com.mls.wms.android.widget.other;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.http.RequestManager;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.YAxisValueFormatter;
import com.mls.wms.android.R;
import com.mls.wms.android.constant.DrawColorUtil;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseActivity;
import com.mls.wms.android.extend.ChartLineMarkerView;
import com.mls.wms.android.model.ApiResult;
import com.mls.wms.android.model.SummaryCenterModel;
import com.mls.wms.android.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2015-09-21.
 */
public class SummaryCenterActivity extends BaseActivity {
    private final static int INBOUND = 1;
    private final static int INVENTORY = 2;
    private final static int OUTBOUND = 3;

    private final static int DAY = 0;
    private final static int WEEK = 1;
    private final static int MONTH = 2;
    private final static int YEAR = 3;


    private LineChart mChart1, mChart2, mChart3;
    private TextView tvDay = null;
    private TextView tvWeek = null;
    private TextView tvMonth = null;
    private TextView tvYear = null;

    private TextView tvInbound = null;
    private TextView tvInventory = null;
    private TextView tvOutbound = null;

    LinearLayout linearLayout = null;
    private AnimDialogFragment progressDialog = null;

    private SummaryCenterModel dataMode;
    private int checkedTab = 0;
    private int checkedWarehouse = -1;


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("TimeType", checkedTab);
        outState.putInt("WarehouseIndex", checkedWarehouse);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_summary_center);

        //弹出框
        progressDialog = new AnimDialogFragment();
        progressDialog.setResId(R.drawable.anim_progress_dialog);

        linearLayout = (LinearLayout) this.findViewById(R.id.act_summary_center_layout);

        mChart1 = (LineChart) this.findViewById(R.id.chart1);
        mChart2 = (LineChart) this.findViewById(R.id.chart2);
        mChart3 = (LineChart) this.findViewById(R.id.chart3);

        setChart(mChart1);
        setChart(mChart2);
        setChart(mChart3);

        tvDay = (TextView) this.findViewById(R.id.act_summary_center_tv_day);
        tvWeek = (TextView) this.findViewById(R.id.act_summary_center_tv_week);
        tvMonth = (TextView) this.findViewById(R.id.act_summary_center_tv_month);
        tvYear = (TextView) this.findViewById(R.id.act_summary_center_tv_year);

        tvInbound = (TextView) this.findViewById(R.id.act_summary_center_tv_inbound);
        tvInventory = (TextView) this.findViewById(R.id.act_summary_center_tv_inventory);
        tvOutbound = (TextView) this.findViewById(R.id.act_summary_center_tv_outbound);

        tvDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData(SummaryCenterActivity.DAY, -1);
            }
        });
        tvWeek.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData(SummaryCenterActivity.WEEK, -1);
            }
        });
        tvMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData(SummaryCenterActivity.MONTH, -1);
            }
        });
        tvYear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData(SummaryCenterActivity.YEAR, -1);
            }
        });

        //默认选中第一个
        if (savedInstanceState != null) {
            int warehouseIndex = savedInstanceState.getInt("WarehouseIndex", -1);
            int type = savedInstanceState.getInt("TimeType", SummaryCenterActivity.DAY);

            this.loadData(type, warehouseIndex);
        } else {
            this.loadData(SummaryCenterActivity.DAY, -1);
        }
    }

    private void loadData(int timeType, final int warehouseIndex) {
        progressDialog.show(getFragmentManager(), this.toString());

        tvDay.setBackgroundResource(R.color.light_gray);
        tvDay.setTextColor(getResources().getColor(R.color.black));

        tvWeek.setBackgroundResource(R.color.light_gray);
        tvWeek.setTextColor(getResources().getColor(R.color.black));

        tvMonth.setBackgroundResource(R.color.light_gray);
        tvMonth.setTextColor(getResources().getColor(R.color.black));

        tvYear.setBackgroundResource(R.color.light_gray);
        tvYear.setTextColor(getResources().getColor(R.color.black));

        String url = "";
        if (timeType == SummaryCenterActivity.DAY) {
            tvDay.setBackgroundResource(R.color.blue);
            tvDay.setTextColor(getResources().getColor(R.color.white));

            url = ServicePort.getUrl(ServicePort.SummaryCenter_Day);
            checkedTab = SummaryCenterActivity.DAY;
        } else if (timeType == SummaryCenterActivity.WEEK) {
            tvWeek.setBackgroundResource(R.color.blue);
            tvWeek.setTextColor(getResources().getColor(R.color.white));

            url = ServicePort.getUrl(ServicePort.SummaryCenter_Week);
            checkedTab = SummaryCenterActivity.WEEK;
        } else if (timeType == SummaryCenterActivity.MONTH) {
            tvMonth.setBackgroundResource(R.color.blue);
            tvMonth.setTextColor(getResources().getColor(R.color.white));

            url = ServicePort.getUrl(ServicePort.SummaryCenter_Month);
            checkedTab = SummaryCenterActivity.MONTH;
        } else if (timeType == SummaryCenterActivity.YEAR) {
            tvYear.setBackgroundResource(R.color.blue);
            tvYear.setTextColor(getResources().getColor(R.color.white));

            url = ServicePort.getUrl(ServicePort.SummaryCenter_Year);
            checkedTab = SummaryCenterActivity.YEAR;
        }

        get(url, null, new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                String errorMsg = null;
                try {
                    ApiResult result = new ApiResult();
                    result = result.parseJson(s);
                    if (result != null && result.getSuccess() == true) {
                        if (result.getResult() == null || TextUtils.isEmpty(result.getResult())) {
                            throw new Exception(getResources().getString(R.string.exception_no_data));
                        }

                        SummaryCenterModel model = new SummaryCenterModel();
                        dataMode = model.parseJson(result.getResult());

                        loadWarehouse(dataMode);

                        draw(mChart1, INBOUND, warehouseIndex, dataMode);
                        draw(mChart2, INVENTORY, warehouseIndex, dataMode);
                        draw(mChart3, OUTBOUND, warehouseIndex, dataMode);

                        progressDialog.dismiss();
                        return;
                    } else {
                        errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                    }
                } catch (Exception e) {
                    errorMsg = e.getMessage();
                    e.printStackTrace();
                }

                progressDialog.dismiss();
                if (false == TextUtils.isEmpty(errorMsg)) {
                    Toast.makeText(SummaryCenterActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                progressDialog.dismiss();
                Toast.makeText(SummaryCenterActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        }, 1);
    }

    private void loadWarehouse(SummaryCenterModel model) {
        String[] series = model.getSeries();
        if (series == null || series.length == 0) {
            linearLayout.setVisibility(View.GONE);
        } else {
            linearLayout.removeAllViews();
            for (int i = 0; i < series.length; i++) {
                Button btn = new Button(this);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
                params.weight = 1000;
                params.gravity = Gravity.CENTER;

                btn.setLayoutParams(params);
                btn.setTextSize(18F);
                btn.setTextColor(getResources().getColor(R.color.white));
                btn.setBackgroundColor(getResources().getColor(DrawColorUtil.getColor(model.getSeries().length)[i % DrawColorUtil.getColor(model.getSeries().length).length]));
                //btn.setBackgroundResource(ColorCollection.DEFINE_COLOR[i % ColorCollection.DEFINE_COLOR.length]);
                btn.setText(series[i]);
                btn.setTag(i);
                btn.setOnClickListener(myClickListener);

                linearLayout.addView(btn);
            }
            linearLayout.setVisibility(View.VISIBLE);
        }
    }

    private void setChart(LineChart mChart) {
        ChartLineMarkerView markerView = new ChartLineMarkerView(this, R.layout.chart_line_marker_view);
        mChart.setMarkerView(markerView);

        mChart.setDrawGridBackground(false);
        //mChart.setGridBackgroundColor(getResources().getColor(R.color.white));
        mChart.setDescription("");

        // mChart.setStartAtZero(true);

        // enable value highlighting
        mChart.setHighlightEnabled(true);

        // enable touch gestures
        mChart.setTouchEnabled(true);

        // enable scaling and dragging
        mChart.setDragEnabled(false);
        mChart.setScaleEnabled(false);

        // if disabled, scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(false);

        Legend legend = mChart.getLegend();
        legend.setEnabled(false);
        //legend.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTypeface(_BaseApplication.getOpenSansRegular());
        xAxis.setDrawGridLines(true);
        //xAxis.setGridLineWidth(1f);
        xAxis.setDrawAxisLine(true);
        xAxis.setAxisLineWidth(1f);
        xAxis.setAxisLineColor(getResources().getColor(R.color.gray));
        xAxis.setGridColor(getResources().getColor(R.color.gray));

        //Y轴样式。
        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setValueFormatter(new YAxisValueFormatter() {
            @Override
            public String getFormattedValue(float v, YAxis yAxis) {
                return StringUtils.lpad(10, Double.valueOf(v).intValue());
            }
        });
        leftAxis.setTypeface(_BaseApplication.getOpenSansRegular());
        leftAxis.setDrawGridLines(true);
        //leftAxis.setGridLineWidth(1f);
        leftAxis.setDrawAxisLine(true);
        leftAxis.setAxisLineWidth(1f);
        leftAxis.setAxisLineColor(getResources().getColor(R.color.gray));
        leftAxis.setGridColor(getResources().getColor(R.color.gray));
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);

        //Y坐标
        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setEnabled(false);
    }


    private void draw(LineChart mChart, int chartType, int warehouseIndex, SummaryCenterModel model) {
        this.checkedWarehouse = warehouseIndex;
        mChart.resetTracking();

        //X坐标数据
        List<String> xVals = new ArrayList<String>();
        for (String item : model.getLabels()) {
            xVals.add(item);
        }

        //数据集
        int beginIndex = 0;
        int endIndex = model.getSeries().length;
        if (warehouseIndex != -1) {
            beginIndex = warehouseIndex;
            endIndex = warehouseIndex + 1;
        }
        ArrayList<LineDataSet> dataSets = new ArrayList<LineDataSet>();
        for (int z = beginIndex; z < endIndex; z++) {

            ArrayList<Entry> values = new ArrayList<Entry>();

            int[] data = null;
            if (chartType == SummaryCenterActivity.INBOUND) {
                data = model.getInbData()[z];
            } else if (chartType == SummaryCenterActivity.INVENTORY) {
                data = model.getOnHandData()[z];
            } else if (chartType == SummaryCenterActivity.OUTBOUND) {
                data = model.getOubData()[z];
            }

            for (int i = 0; i < data.length; i++) {
                values.add(new Entry(data[i], i));
            }

            LineDataSet d = new LineDataSet(values, model.getSeries()[z]);

            d.setLineWidth(1.0f);
            d.setCircleSize(3.0f);

            int color = getResources().getColor(DrawColorUtil.getColor(model.getSeries().length)[z % DrawColorUtil.getColor(model.getSeries().length).length]);
            d.setColor(color);
            d.setCircleColor(color);
            d.setDrawCircles(true);
            d.setDrawCircleHole(false);
            d.setDrawValues(false);
            dataSets.add(d);
        }

        if (warehouseIndex == -1) {
            int sum = 0;
            //入库
            if (model.getInbTotal() == null) {
                sum = 0;
            } else {
                for (int item : model.getInbTotal()) {
                    sum += item;
                }
            }
            tvInbound.setText("入库[" + sum + "]");
            //库存
            sum = 0;
            if (model.getOnHandTotal() == null) {
                sum = 0;
            } else {
                for (int item : model.getOnHandTotal()) {
                    sum += item;
                }
            }
            tvInventory.setText("库存[" + sum + "]");
            //出库
            sum = 0;
            if (model.getOubTotal() == null) {
                sum = 0;
            } else {
                for (int item : model.getOubTotal()) {
                    sum += item;
                }
            }
            tvOutbound.setText("出库[" + sum + "]");
        } else {
            int value = 0;
            //入库
            if (model.getInbTotal() == null) {
                value = 0;
            } else {
                value = model.getInbTotal()[warehouseIndex];
            }
            tvInbound.setText("入库[" + value + "]");
            //库存
            if (model.getOnHandTotal() == null) {
                value = 0;
            } else {
                value = model.getOnHandTotal()[warehouseIndex];
            }
            tvInventory.setText("库存[" + value + "]");
            //出库
            if (model.getOubTotal() == null) {
                value = 0;
            } else {
                value = model.getOubTotal()[warehouseIndex];
            }
            tvOutbound.setText("出库[" + value + "]");
        }

        LineData data = new LineData(xVals, dataSets);
        mChart.setData(data);
        mChart.invalidate();
    }

    @Override
    public int getTopNameResId() {
        return R.string.title_summary_center;
    }

    @Override
    public boolean getScannerVisible() {
        return false;
    }

    private View.OnClickListener myClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int warehouseIndex = Integer.parseInt(v.getTag().toString());

            draw(mChart1, INBOUND, warehouseIndex, dataMode);
            draw(mChart2, INVENTORY, warehouseIndex, dataMode);
            draw(mChart3, OUTBOUND, warehouseIndex, dataMode);
        }
    };
}
